﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Telerik.Windows;
using Telerik.Windows.Controls.DragDrop;

namespace Rio.Framework.Pages.AppCode.Helpers.Behavior
{
    public class AutoScrollBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();

            EventManager.RegisterClassHandler(typeof(ScrollViewer), RadDragAndDropManager.DropQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnListBoxScrollViewerDropQuery), true);
        }

        private static void OnListBoxScrollViewerDropQuery(object sender, DragDropQueryEventArgs e)
        {
            var scrollViewer = sender as ScrollViewer;

            if (scrollViewer != null)
            {

                var currentDragPoint = e.Options.CurrentDragPoint;

                var generalTransform = scrollViewer.TransformToVisual(Application.Current.RootVisual);

                var topLeft = generalTransform.Transform(new Point(0, 0));
                var relative = new Point(currentDragPoint.X - topLeft.X, currentDragPoint.Y - topLeft.Y);

                if (relative.Y > 0 && relative.Y < 40)
                {
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - (20 * ((40 - relative.Y) / 40)));
                }

                if (relative.Y > scrollViewer.ActualHeight - 40 && relative.Y < scrollViewer.ActualHeight)
                {
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + (20 * ((40 - (scrollViewer.ActualHeight - relative.Y)) / 40)));
                }

                if (relative.X > 0 && relative.X < 40)
                {
                    scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - (20 * ((40 - relative.X) / 40)));
                }

                if (relative.X > scrollViewer.ActualWidth - 40 && relative.X < scrollViewer.ActualWidth)
                {
                    scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + (20 * ((40 - (scrollViewer.ActualWidth - relative.X)) / 40)));
                }
            }
        }
    }
}
